//定义小仓库
import { defineStore } from "pinia";
import { ref } from "vue";
//引入请求函数
import { reqUserCartList, reqUpskuNumCart, reqCheck, reqDelete } from '../api/cart/cart';
export const cartListStore = defineStore('cartInfo', () => {
    const cartList = ref([])
    const Price = ref(0)
    //获取商品列表
    const getcart = async () => {
        let result: any = await reqUserCartList();
        console.log(result);
        cartList.value = result.data[0].cartInfoList || [];
    };
    //商品加1
    const addToCart = async (skuId: any, skuNum: any) => {
        let result: any = await reqUpskuNumCart(skuId, skuNum);
    }
    //商品减1
    const minusCart = async (skuId: any, skuNum: any) => {
        let result: any = await reqUpskuNumCart(skuId, skuNum);
    }

    //商品状态
    const checkbox = async (skuId: any, checked: any) => {
        let result = await reqCheck(skuId, checked)
    }
    //删除商品
    const removeGoodById = async (skuId: any) => {
        let result = await reqDelete(skuId)
    }
    //全选状态
    const AllChecked = async (Checked: any) => {
        let arr: any = [];
        cartList.value.forEach((good: any) => {
            let ps = checkbox(good.skuId, Checked)
            arr.push(ps)
        });
        return Promise.all(arr);
    }
    //提交的订单价
    const totalPrice = () => {
        let arr: any = [];
        cartList.value.forEach((item: any) => {
            if (item.isChecked == 1) {
                arr.push(item);
            }
        });
        return Price.value = arr.reduce(
            (pre: any, next: any) => pre + next.skuNum * next.cartPrice,
            0
        );
    };

    return { cartList, Price, getcart, addToCart, minusCart, checkbox, removeGoodById, AllChecked, totalPrice }
})